#ifndef _ROT_HPP
#define _ROT_HPP

extern void showSettingsQrcodeTask();
extern void pageShow(int pageNum);

static TaskHandle_t rotOpH;
static rotary_encoder_t *encoder = NULL;
static int currentValue = 0;
static uint32_t pcntUnit = 0;
static uint64_t rotCPressStartTime = 0;
static bool rotCPress = false;

void (*rotA)() = NULL;
void (*rotB)() = NULL;
void (*rotC)() = NULL;

void *lastA;
void *lastB;
void *lastC;

void rotCFunDefault() {
	pageShow(PAGE_SETTINGS);
}

void rotFunSet(void *a, void *b, void *c) {
	lastA = rotA;
	lastB = rotB;
	lastC = rotC;

	rotA = a;
	rotB = b;
	rotC = c;
}

void rotFunGoBack() {
	rotA = lastA;
	rotB = lastB;
	rotC = lastC;
}

void rotOp() {
	uint32_t bit;
	while(1) {
		// printf("rotOP do\n");
		xTaskNotifyWait(
			ULONG_MAX,
			ULONG_MAX,
			&bit,
			portMAX_DELAY
		);
		if(((bit & BIT0) != 0) && rotA != NULL) {
			rotA();
		}
		if(((bit & BIT1) != 0) && rotB != NULL) {
			rotB();
		}
		if(((bit & BIT2) != 0) && rotC != NULL) {
			rotC();
		}
	}
	vTaskDelete(NULL);
}

void rotInit() {
	rotary_encoder_config_t rotConfig = ROTARY_ENCODER_DEFAULT_CONFIG((rotary_encoder_dev_t) pcntUnit, CONFIG_PIN_ROT_CLK, CONFIG_PIN_ROT_DT);
	
	ESP_ERROR_CHECK(rotary_encoder_new_ec11(&rotConfig, &encoder));
	ESP_ERROR_CHECK(encoder->set_glitch_filter(encoder, 1));
	ESP_ERROR_CHECK(encoder->start(encoder));

	gpio_config_t pinRotC = {
		.intr_type = 0,
		.mode = GPIO_MODE_INPUT,
		.pin_bit_mask = (1ULL << CONFIG_PIN_ROT_SW),
		.pull_up_en = 1
	};
	gpio_config(&pinRotC);

	// 编码器操作
	xTaskCreatePinnedToCore(rotOp, "rotOp", 1024 * 2, NULL, 0, &rotOpH, 1);

	rotFunSet(NULL, NULL, &rotCFunDefault);

	while(1) {
		int getValue = encoder -> get_counter_value(encoder);
		if(getValue != currentValue) {
			// 顺时针旋转
			if(getValue > currentValue) {
				xTaskNotify(rotOpH, BIT0, eSetValueWithoutOverwrite);
			}
			// 逆时针旋转
			else if(getValue < currentValue) {
				xTaskNotify(rotOpH, BIT1, eSetValueWithoutOverwrite);
			}
			currentValue = getValue;
		}
		// 旋转编码器按键按下
		if(gpio_get_level(CONFIG_PIN_ROT_SW) == 0) {
			DELAY(30);
			if(!rotCPress) {
				rotCPress = true;
				rotCPressStartTime = getTimeMs();
			}
			else {
				if(getTimeMs() - rotCPressStartTime > 1500) {
					rotCPress = false;
					rotCPressStartTime = 0;
					
					xTaskCreate(showSettingsQrcodeTask, "showSettingsQrcodeTask", 1024 * 9, NULL, 0, NULL);
					// DELAY(100);
				}
			}
		}
		else if(gpio_get_level(CONFIG_PIN_ROT_SW) == 1 && rotCPress) {
			rotCPress = false;
			xTaskNotify(rotOpH, BIT2, eSetValueWithoutOverwrite);
		}
        DELAY(150);
	}
	vTaskDelete(NULL);

}
#endif